package com.wjk.cms.service.impl;

import com.wjk.cms.dao.MessageRepository;
import com.wjk.cms.pojo.Message;
import com.wjk.cms.service.MessageService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.Predicate;
import java.util.ArrayList;
import java.util.List;

/**
 * @author WUGN
 * @des
 * @date 2021/10/12 9:15
 */
@Service
public class MessageServiceImpl implements MessageService {
    @Autowired
    private MessageRepository messageRepository;


    @Override
    public List<Message> list(Long userId, String status, Integer pageNo, Integer pageSize) {
        if(pageNo==null || pageNo<1){
            return messageRepository.findAll((root, query, cb) -> {
                List<Predicate> predicates = new ArrayList<>();
                if (userId!=null && userId>0) {
                    predicates.add(cb.equal(root.get("userId"),userId));

                }
                if (StringUtils.isNotBlank(status)) {
                    predicates.add(cb.equal(root.get("status"),status));

                }


                return cb.and(predicates.toArray(new Predicate[0]));
            }, Sort.by(Sort.Order.desc("createTime")));
        }else {
            return messageRepository.findAll((root, query, cb) -> {
                List<Predicate> predicates = new ArrayList<>();
                if (userId!=null && userId>0) {
                    predicates.add(cb.equal(root.get("userId"),userId));

                }
                if (StringUtils.isNotBlank(status)) {
                    predicates.add(cb.equal(root.get("status"),status));

                }

                return cb.and(predicates.toArray(new Predicate[0]));
            }, PageRequest.of(pageNo - 1, pageSize, Sort.Direction.DESC, "createTime")).getContent();
        }
    }

    @Override
    public Message getById(Long messageId) {
        return messageRepository.getOne(messageId);
    }

    @Override
    public void save(Message message) {
        messageRepository.save(message);
    }


}
